package com.leyou.task.lock;

import org.springframework.data.redis.core.StringRedisTemplate;

import java.util.UUID;
import java.util.concurrent.TimeUnit;

/**
 * redis锁
 */
public class SimpleRedisLock implements RedisLock {

    private StringRedisTemplate redisTemplate; // 传入模板用于操作redis

    private String key; // 锁对应key：lock
    //private final static String VALUE = "1";

    /**
     * 标记
     */
    private final static String ID = UUID.randomUUID().toString();

    public SimpleRedisLock(StringRedisTemplate redisTemplate, String key){
        this.redisTemplate = redisTemplate;
        this.key = key;
    }

    //加锁
    @Override
    public boolean lock(long releaseTime) {
        // 以线程的id作为值
        String value = ID + Thread.currentThread().getId();
        // 如果redis中没有就能插入，如果能插入就返回true
        Boolean boo = redisTemplate.opsForValue().setIfAbsent(key, value, releaseTime, TimeUnit.SECONDS);
        // 结果
        return boo!=null && boo;
    }

    //释放锁
    @Override
    public void unlock() {
        // 以线程的id作为值
        String value = ID + Thread.currentThread().getId();
        // 从缓存中获取锁
        String val = redisTemplate.opsForValue().get(key);
        if(value.equals(val)){
            redisTemplate.delete(key);
        }
    }
}
